import re
import time
from flask import request
from flask_restful import abort
from flask_login import current_user, login_user
from funcy import project
from sqlalchemy.orm.exc import NoResultFound
from sqlalchemy.exc import IntegrityError
from funcy import partial

from redash import models, limiter
from redash.permissions import (
    require_permission,
    require_admin_or_owner,
    is_admin_or_owner,
    require_permission_or_owner,
    require_admin_default,
)
from redash.handlers.base import (
    BaseResource,
    require_fields,
    get_object_or_404,
    paginate,
    order_results as _order_results,
)

from redash.authentication.account import (
    invite_link_for_user,
    send_invite_email,
    send_password_reset_email,
    send_verify_email,
)
from redash.settings import parse_boolean
from redash import settings

class ContractAmountNewResource(BaseResource):
    # def get(self):
    #     result = models.ContractAmount.get_id()
    #     return result[0]

    @require_admin_default
    def post(self):
        req = request.get_json(force=True)
        # require_fields(req, ("code","name"))

        contractamount = models.ContractAmount(
        amount=req["amount"],
        userid=req["userid"],
        bill_date = req["bill_date"],
        message =req["message"],
        warn_date = req["warn_date"],
        warn_message = req["warn_message"],
        contractsid = req["contractsid"],
        amount_enum = req["amount_enum"],
        sourcetype =req["sourcetype"],
        sourceid =req["sourceid"],
        )

        try:
            models.db.session.add(contractamount)
            models.db.session.commit()
        except IntegrityError as e:
            # if "code" in str(e):
            #     abort(400, message="编号已存在.")
            abort(500)


class ContractAmountResource(BaseResource):
    def get(self, contractamount_id):
        result = models.ContractAmount.get_by_id(contractamount_id)
        return result.to_dict()

    @require_admin_default
    def post(self, contractamount_id):
        req = request.get_json(force=True)
        # require_fields(req, ("code","name"))

        contractamount = models.ContractAmount.get_by_id(contractamount_id)
        params = dict(userid=req["userid"], bill_date=req["bill_date"], contractsid=req["contractsid"], amount_enum=req["amount_enum"],
                sourceid=req["sourceid"],amount=req["amount"],
                sourcetype=req["sourcetype"],message=req["message"])
        try:
            self.update_model(contractamount, params)
            models.db.session.commit()
        except IntegrityError as e:
            # if "code" in str(e):
            #     abort(400, message="编号已存在.")
            abort(500)

class ContractAmountdeleteResource(BaseResource):
    @require_admin_default
    def post(self, contractamount_id):
        contractamount =  models.ContractAmount.get_by_id(contractamount_id)
        models.db.session.delete(contractamount)
        models.db.session.commit()

class ContractAmountListResource(BaseResource):
    def post(self):
        req = request.get_json(force=True)
        page = req["page"]
        page_size = req["pagesize"]
        contractsid = req["contractsid"]
        strwhere =" t1.contractsid ="+str(contractsid)

        strgetfield =""" t1.*,t2.typename"""

        tblname = """public.contractamount t1 inner join
            (select unnest(items)->>'value' as typecode,(unnest(items))->>'title' as typename
            From enums where code='amount_enum') t2 on t1.amount_enum=t2.typecode"""
        orderfield ="t1.id"
        result = models.ContractApply.get_pagequery(tblname,strgetfield,orderfield,page_size,page,0,strwhere)
        return result[0]
